package cn.touna.jss.modules.custom.auth;

import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.custom.auth.entity.AuthCardEntity;
import cn.touna.jss.modules.custom.auth.entity.AuthRealNameEntity;
import cn.touna.jss.modules.third.tx.TianXingService;
import cn.touna.jss.modules.third.tx.entity.UnionPayRequest;
import cn.touna.jss.modules.third.zhongan.ZhonganService;
import cn.touna.jss.modules.third.zhongan.entity.ZhonganRequestEntity;
import cn.touna.risk.api.domain.Response;
import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import com.alibaba.fastjson.JSONObject;
import com.touna.loan.log.service.TracerContextUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 银行卡认证调用组件
 */
@Service
public class AuthCardService {
    private static final Logger logger = LogManager.getLogger(AuthCardService.class);

    @Autowired
    private TianXingService tianXingService;

    @Autowired
    private ZhonganService zhonganService;


    private static final String COMPARE_SAME = "SAME";

    /**
     * 调用天行实名认证
     * @param authCardEntity
     * @return
     */
    @ApiMapping(value = "auth.authCard4Elements",desc = "复合数据.四要验证素（天行/众安）")
    public Response authCard4Elements(AuthCardEntity authCardEntity) {
        ValidUtil.checkRequestParams(authCardEntity);
        try {
            Response  response= zhonganAuthCard(authCardEntity);
            if (response != null && response.getCode().equals("200")) {
               return response;
           }
           return  tianxingAuthCard(authCardEntity);
         } catch (Exception e) {
            logger.error("PRO 调用【四要素实名认证-txIdCardVerify】异常,params:{}，msg:{}", authCardEntity, e.getMessage());
            return ResponseFactory.fail(SystemErrorCodeEnum.CRS_SYSTEM_FAILED, e.getMessage());
        }
    }

    private Response tianxingAuthCard(AuthCardEntity authCardEntity) {
        UnionPayRequest.FourElementRequest requestEntity= new UnionPayRequest.FourElementRequest();
        requestEntity.setMobile(authCardEntity.getMobile());
        requestEntity.setIdCard(authCardEntity.getIdCard());
        requestEntity.setBankCardNo(authCardEntity.getBankCardNo());
        requestEntity.setName(authCardEntity.getName());
        Response response = tianXingService.fourElementValidate(requestEntity);
        if(response.getCode().equals("200")){
            JSONObject data = new JSONObject();
            data.put("idCard",authCardEntity.getIdCard());
            data.put("name",authCardEntity.getName());
            data.put("mobile",authCardEntity.getMobile());
            data.put("bankCardNo",authCardEntity.getBankCardNo());
            response.setData(data);
            return response;
        }
        return null;
    }

    private Response zhonganAuthCard(AuthCardEntity authCardEntity) {
        ZhonganRequestEntity.AuthCard4ElementsRequest    request = new ZhonganRequestEntity.AuthCard4ElementsRequest();
        request.setBankCardNo(authCardEntity.getBankCardNo());
        request.setIdCard(authCardEntity.getIdCard());
        request.setMobile(authCardEntity.getMobile());
        request.setName(authCardEntity.getName());
        Response response=zhonganService.authCard4Elements(request);
        if(response.getCode().equals("200")){
            JSONObject data = new JSONObject();
            data.put("idCard",authCardEntity.getIdCard());
            data.put("name",authCardEntity.getName());
            data.put("mobile",authCardEntity.getMobile());
            data.put("bankCardNo",authCardEntity.getBankCardNo());
            response.setData(data);
            return response;
        }
        response.setMsg("验证失败,信息不匹配");
        return response;
    }

    /**
     * 调用众安身份认证
     * @param authRealNameEntity
     * @return
     */
    private Response zhonganAuthRealIdentity(AuthRealNameEntity authRealNameEntity) {
        JSONObject resultJson = new JSONObject();
        Response response = null;
        try {
            ZhonganRequestEntity.AuthRealIdentityRequest requestEntity = new ZhonganRequestEntity.AuthRealIdentityRequest();
            BeanUtils.copyProperties(authRealNameEntity, requestEntity);
            requestEntity.setRequestNo(TracerContextUtil.getTraceId());
            response = zhonganService.authRealIdentity(requestEntity);
            if (response.checkIfSuccess()) {
                JSONObject jsonObject = JSONObject.parseObject(response.getData().toString());
                JSONObject head = (JSONObject) jsonObject.get("head");
                String rspCode = (String) head.get("rspCode");
                JSONObject body = jsonObject.getJSONObject("body");
                JSONObject rspInfo = body.getJSONObject("rspInfo");
                JSONObject reqInfo = (JSONObject) body.get("reqInfo");
                String quotaValue = (String) rspInfo.get("quotaValue");
                resultJson.put("name", reqInfo.get("name"));
                resultJson.put("idNo", authRealNameEntity.getIdCard());
                if (rspCode.equals("0000")) {
                    if (quotaValue.equals("Y")) {
                        resultJson.put("compareStatus", "SAME");
                        resultJson.put("compareStatusDesc", "一致");
                    } else {
                        resultJson.put("compareStatus", "DIFFERENT");
                        resultJson.put("compareStatusDesc", "不一致");
                    }
                    response.success(SystemErrorCodeEnum.SYSTEM_REQUEST_SUCC);
                    response.setData(resultJson);
                    response.setMsg("请求成功");
                }
            } else {
                response.fail();
            }
            return response;
        } catch (Exception e) {
            logger.error("PRO 调用【众安身份认证 - authRealIdentity】异常，params:{},msg:{}", authRealNameEntity, e.getMessage());
            return ResponseFactory.fail(SystemErrorCodeEnum.CRS_SYSTEM_FAILED, e.getMessage());
        }
    }

    private boolean isSame(Response response) {
        JSONObject jsonObject = JSONObject.parseObject(response.getData().toString());
        String compareStatus = (String) jsonObject.get("compareStatus");
        if (COMPARE_SAME.equals(compareStatus)) {
            return true;
        }
        return false;
    }
}
